/*
import { asyncRouterMap, constantRouterMap } from '@/config/router.config'

/!**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permission
 * @param route
 * @returns {boolean}
 *!/
function hasPermission (permission, route) {
  if (route.meta && route.meta.permission) {
    let flag = false
    for (let i = 0, len = permission.length; i < len; i++) {
      flag = route.meta.permission.includes(permission[i])
      if (flag) {
        return true
      }
    }
    return false
  }
  return true
}

/!**
 * 单账户多角色时，使用该方法可过滤角色不存在的菜单
 *
 * @param roles
 * @param route
 * @returns {*}
 *!/
// eslint-disable-next-line
function hasRole(roles, route) {
  if (route.meta && route.meta.roles) {
    return route.meta.roles.includes(roles.id)
  } else {
    return true
  }
}

function filterAsyncRouter (routerMap, roles) {
  const accessedRouters = routerMap.filter(route => {
    if (hasPermission(roles.permissionList, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
  },
  actions: {
    GenerateRoutes ({ commit }, data) {
      return new Promise(resolve => {
        const { roles } = data
        const accessedRouters = filterAsyncRouter(asyncRouterMap, roles)
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    },
  },
}

export default permission
*/

import { asyncRouterMap, constantRouterMap as constantRoutes } from '@/config/router.config'
import { getMenuTreeByToken } from '@/api/system/menu'
// import Layout from '@/layout'
// import ParentView from '@/components/ParentView'

import { BasicLayout, BlankLayout } from '@/layouts'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }

    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

export function parseMenuByRouter(menus, isOuter) {
  const res = []

  menus.forEach(menu => {
    if (menu.menuType !== 'BUTTON') {
      const tmp = {
        path: menu.menuUrl,
        name: menu.menuUrl,
        component: loadView(menu.menuType, isOuter, menu.componentPath),
        hidden: menu.isShow === 'HIDDEN',
        meta: {
          title: menu.name,
          icon: menu.menuIcon,
          keepAlive: menu.keepAlive === 'YES'
        }
      }
      if (menu.menuType === 'DIRECTORY') {
        tmp.redirect = menu.redirect
      }

      if (menu.children) {
        tmp.children = parseMenuByRouter(menu.children, false)
      }

      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [...constantRoutes],
  addRouters: [],
  isReq: false
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRouters = routes
    state.routes = constantRoutes.concat(routes)
    state.isReq = true
  },
  SET_REQ: (state, req) => {
    state.isReq = req
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise((resolve, reject) => {
      // 使用接口调用菜单树
      /* getMenuTreeByToken().then((res) => {
        if (res && res.code === 'A00000') {
          const menus = res.data || []
          const accessedRoutes = parseMenuByRouter(menus, true)

          const asyncRouter = [
            {
              path: '/',
              name: 'index',
              component: BasicLayout,
              meta: { title: 'menu.home' },
              redirect: '/caution/alarmRecord',
              children: [

              ]
            },
            {
              path: '*', redirect: '/404', hidden: true
            }
          ]

          asyncRouter[0].children = accessedRoutes

          commit('SET_ROUTES', asyncRouter)
          resolve(asyncRouter)
        } else {
          reject(res)
        }
      }).catch((err) => {
        reject(err)
      })*/

      // 使用登录接口调用菜单树
      // const userInfo = JSON.parse(localStorage.getItem('user_info'))
      //
      // let accessedRoutes
      // if (userInfo && userInfo.menuTreeVoList) {
      //   accessedRoutes = parseMenuByRouter(userInfo.menuTreeVoList, true)
      // }
      // commit('SET_ROUTES', accessedRoutes)
      // resolve(accessedRoutes)

      commit('SET_ROUTES', asyncRouterMap)

      resolve(asyncRouterMap)
    })
  }
}

export default {
  state,
  mutations,
  actions
}

export const loadView = (routerType, isOuter, componentPath) => { // 路由懒加载
  if (routerType === 'DIRECTORY') {
    return BlankLayout
  }

  return (resolve) => require([`@/views/${componentPath}.vue`], resolve)
}
